﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SdmxMl.Structure;
using SdmxMl.Common;
using SdmxMl.Manager;


namespace ActivityMgr.HGDE
{
    public class ValidityCode
    {
        /// <summary>Date for validity start (inclusive)</summary>
        public DateTime DtFrom { get; private set; }
        /// <summary>Date for validity End (inclusive)</summary>
        public DateTime DtTo { get; private set; }

        /// <summary>RN historical code</summary>
        public CodeType HistoryCode { get; private set; }
        /// <summary>OFS Equivalent code</summary>
        public string OfsCode { get; private set; }

        /// <summary>ID code for previous radiation</summary>
        public string Inscription { get; private set; }
        
        /// <summary>ID code for next inscription</summary>
        public string Radiation { get; private set; }

        public List<ValidityCode> PreviousList { get; set; }
        public List<ValidityCode> NextList { get; set; }

        #region Construction

        public ValidityCode(DateTime f, DateTime t, CodeType cHist)
        {
            DtFrom = f;
            DtTo = t;
            HistoryCode = cHist;
            OfsCode = cHist.AnnotationList.GetTextOfAnnotationType("CODE_OFS");
            if (OfsCode.Length == 0)
                throw new ApplicationException("No OFS code defined for history code: " + cHist.Id);
            Inscription = cHist.AnnotationList.GetTextOfAnnotationType("INSCRIPTION");
            Radiation = cHist.AnnotationList.GetTextOfAnnotationType("RADIATION");

        }
        #endregion
    }

    public class ValidityCodelist : List<ValidityCode>
    {

        public ValidityCodelist() : base() { }
        public ValidityCodelist(int capacity) : base(capacity) { }

        public List<ValidityCode> FindOfs(string ofsCode)
        {
             List<ValidityCode> lvc = FindAll(x => x.OfsCode == ofsCode);
            lvc.Sort(delegate(ValidityCode p1, ValidityCode p2)
            { return p1.DtFrom.CompareTo(p2.DtFrom); });
            return lvc;
        }

        public List<ValidityCode> FindPrevious(string linkCode)
        {
            return FindAll(x => x.Radiation == linkCode);
        }

        public List<ValidityCode> FindNext(string linkCode)
        {
            return FindAll(x => x.Inscription == linkCode);
        }

        public void UpdateLinks()
        {
            foreach (ValidityCode vc in this)
            {
                if (vc.Radiation.Length > 0)
                    vc.NextList = FindNext(vc.Radiation);
                if (vc.Inscription.Length > 0)
                    vc.PreviousList = FindPrevious(vc.Inscription);
            }

        }
    }
}
